import React, { useState, useEffect, useMemo, useContext } from 'react';
import {
  Table,
  Card,
  Switch,
  Button,
  Space,
  Typography,
  Popover,
  Checkbox,
  Breadcrumb,
} from '@arco-design/web-react';
import { IconFilter } from '@arco-design/web-react/icon';
import useLocale from '@/utils/useLocale';
import SearchForm from './form';
import locale from './locale';
import styles from './style/index.module.less';
import { getColumns } from './constants';
import { Search } from '@/api/modules/myTask';
import { GlobalContext } from '@/context';
import { useHistory } from 'react-router-dom';
import useIsMountedRef from '@/utils//useIsMountedRef';
import cs from 'classnames';
import Task from '@/assets/task.svg';
import useStorageJson from '@/utils/useStorageJson';
import { useSelector } from 'react-redux';
import { GlobalState } from '@/store';
const { Title } = Typography;
import isEmpty from 'lodash/isEmpty';
import debounce from 'lodash/debounce';
import { SorterInfo } from '@arco-design/web-react/es/Table/interface';

function SearchTable() {
  const t = useLocale(locale);
  const { lang, rtl } = useContext(GlobalContext);
  const { userInfo } = useSelector((state: GlobalState) => state);
  const history = useHistory();

  const tableCallback = async (record, type) => {
    if (type === 'details') {
      history.push({
        pathname: `/MyTasks/Detail`,
        search: `?fromPath=task&refNumber=${record.refNumber}`,
      });
    }
  };

  const [tableColumns, setTableColumns] = useStorageJson(
    `${userInfo.id}_myTask_tableColumns`,
    [
      'refNumber',
      'emirateEntity',
      'violationType',
      'violationDesc',
      'violationAdditionalDetails',
      'createdAt',
      'emirateEntityAr',
      'fullName',
    ]
  );

  const options = [
    {
      label: t['searchTable.columns.number'],
      value: 'refNumber',
      disabled: true,
      width: 290,
    },
    {
      label: t['searchTable.columns.name'],
      value: 'emirateEntity',
      width: 170,
    },
    {
      label: t['searchTable.columns.nameAr'],
      value: 'emirateEntityAr',
      width: 170,
    },
    {
      label: t['searchTable.columns.type'],
      value: 'violationType',
      width: 200,
    },
    {
      label: t['searchTable.columns.desc'],
      value: 'violationDesc',
      width: 200,
    },
    {
      label: t['searchTable.columns.AdditionalDetails'],
      value: 'violationAdditionalDetails',
      width: 200,
    },

    {
      label: t['searchTable.columns.fullName'],
      value: 'fullName',
      width: 180,
    },
    {
      label: t['searchTable.columns.created'],
      value: 'createdAt',
      width: 200,
    },
  ];

  const columns = useMemo(
    () => getColumns(t, tableCallback, tableColumns, options, lang),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [t, tableColumns]
  );

  const width = useMemo(
    () => {
      return columns.reduce((sum, { width = 0 }) => sum + width, 0) || 0;
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [columns]
  );

  const [data, setData] = useState([]);

  const [pagination, setPatination] = useStorageJson(`myTask_pagination`, {
    sizeOptions: [10, 20, 50, 100],
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [onlyUnRead, setOnlyUnRead] = useStorageJson(
    'myTask_onlyUnRead',
    false
  );
  const [formParams, setFormParams] = useStorageJson('myTask_formParams', {});
  const isMountedRef = useIsMountedRef();
  useEffect(() => {
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    pagination.current,
    pagination.pageSize,
    JSON.stringify(formParams),
    JSON.stringify(onlyUnRead),
  ]);

  async function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    try {
      const { data } = await Search({
        pageNo: current,
        pageSize,
        ...formParams,
        onlyUnRead: onlyUnRead,
      });
      if (isMountedRef.current) {
        setData(data.data);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: data.count,
        });
        setLoading(false);
      }
    } catch (e) {
      setLoading(false);
    }
  }

  function onChangeTable({ current, pageSize }, sorter: SorterInfo) {
    const { direction, field } = sorter;
    if (direction) {
      const sort = [];
      const obj = Object.create({});
      if (field == 'emirateEntity' || field == 'emirateEntityAr') {
        obj.field = 'emirate_entity';
      }
      if (field == 'refNumber') {
        obj.field = 'ref_number';
      }
      obj.asc = direction == 'ascend';
      sort.push(obj);
      setFormParams({ ...formParams, sort });
    } else {
      const updatedFormParams = { ...formParams, sort: undefined };
      delete updatedFormParams.sort;
      console.log(updatedFormParams);
      setFormParams(updatedFormParams);
    }

    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }

  const handleSearch = debounce((params) => {
    if (params.Date) {
      params.start = params.Date[0];
      params.end = params.Date[1];
    }

    if (loading && isEmpty(params)) return;
    setPatination({ ...pagination, current: 1 });
    setFormParams(params);
  }, 300);

  const CheckboxGroup = Checkbox.Group;

  const tableColumnsFilter = () => (
    <CheckboxGroup
      direction="vertical"
      options={options}
      value={tableColumns}
      onChange={(value) => setTableColumns(value)}
    />
  );

  return (
    <>
      <div className={cs(styles['layout-breadcrumb'], rtl ? 'rtl' : '')}>
        <Breadcrumb>
          <Breadcrumb.Item>
            <Task
              style={{
                [rtl ? 'marginLeft' : 'marginRight']: '8px',
              }}
              className={cs(
                rtl ? styles['rtl-icon'] : styles.icon,
                'arco-icon'
              )}
            />
            {t['menu.myTasks']}
          </Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <Card>
        {/* <Title heading={6} className={styles['page-title']}>
          {t['searchTable.form.title']}
        </Title> */}
        <SearchForm onSearch={handleSearch} value={formParams} />

        <div className={styles['button-group']}>
          <Space>
            {/* <Button type="primary" icon={<IconPlus />}>
            {t['searchTable.operations.add']}
          </Button> */}
          </Space>
          <Space>
            <Switch checked={onlyUnRead} onChange={setOnlyUnRead} />
            <span>{t['searchTable.operations.Unread']}</span>
            <span></span>
            <Popover
              position="bottom"
              trigger="click"
              content={tableColumnsFilter}
            >
              <Button icon={<IconFilter />}>
                {t['searchTable.operation.filter']}
              </Button>
            </Popover>
          </Space>
        </div>
        <Table
          border={{
            wrapper: true,
            cell: true,
          }}
          scroll={{
            x: width,
          }}
          rowKey="id"
          loading={loading}
          onChange={onChangeTable}
          pagination={pagination}
          columns={columns}
          data={data}
          rowClassName={(a) => {
            return a?.status?.key;
          }}
        />
      </Card>
    </>
  );
}

export default SearchTable;
